using System;
using System.Data;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Health.Samples.PatientConnect.TreyResearch.HealthVaultAdapter;
using System.IO;
using System.Xml;

public partial class ViewPatient : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            HiddenFieldSortOrder.Value = "ASC";
            HiddenFieldExpression.Value = "PatientName";
            if (Session["PracticeFolderName"] != null)
            {
                BindDataWithGrid();
            }
        }
    }

    protected void GrdPatientList_Sorting(object sender, GridViewSortEventArgs e)
    {
        HiddenFieldExpression.Value = e.SortExpression;
        if (HiddenFieldSortOrder.Value != ("ASC"))
        {
            HiddenFieldSortOrder.Value = "ASC";
        }
        else
        {
            HiddenFieldSortOrder.Value = "DESC";
        }
        BindDataWithGrid();

    }

    protected void GrdPatientList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridViewPatientList.PageIndex = e.NewPageIndex;
        BindDataWithGrid();
    }

    /// <summary>
    /// Create patient table
    /// </summary>
    /// <param name="tablePatient">patient detail collection</param>
    /// <returns>patient table</returns>
    private DataTable CreatePatientTable(List<Patient> tablePatient)
    {
        DataTable recordDetails = new DataTable();
        recordDetails.Columns.Add("PatientID");
        recordDetails.Columns.Add("PatientName");
        recordDetails.Columns.Add("Medications");
        recordDetails.Columns.Add("CCR");
        recordDetails.Columns.Add("CCD");
        recordDetails.Columns.Add("LabTests");
        recordDetails.Columns.Add("Enroll");

        for (int currentPatient = 0; currentPatient < tablePatient.Count; currentPatient++)
        {
            string currentPatientId = tablePatient[currentPatient].PatientId.ToString();

            string currentPatientName = string.Format("{0} {1} {2}",
                tablePatient[currentPatient].FirstName.ToString(),
                tablePatient[currentPatient].MiddleName.ToString(),
                tablePatient[currentPatient].LastName.ToString());

            object[] parameters = new object[7];
            parameters[0] = "~/ViewPatientDetails.aspx?PatientId=" + currentPatientId;
            parameters[1] = currentPatientName;
            parameters[2] = CheckFile(Constants.MedicationFolderName, currentPatientId);
            parameters[3] = CheckFile(Constants.CcrFolderName, currentPatientId);
            parameters[4] = CheckFile(Constants.CcdFolderName, currentPatientId);
            parameters[5] = CheckFile(Constants.LabResultsFolderName, currentPatientId);
            if (Convert.ToBoolean(tablePatient[currentPatient].RegisteredWithHealthVault))
            {
                parameters[6] = "Y";
            }
            else
            {
                parameters[6] = "N";
            }
            recordDetails.Rows.Add(parameters);
        }
        return recordDetails;
    }

    /// <summary>
    ///  Read Patient Details from Patient.xml and Bind with Data Grid 
    /// </summary>
    public void BindDataWithGrid()
    {
        Patient getPatient = new Patient(Server.MapPath("Data/" + Session["PracticeFolderName"].ToString() + @"\" + Constants.PatientXmlFileName));
        List<Patient> tablePatient = getPatient.SelectPatientRecords("Active=True");
        DataTable recordDetails = CreatePatientTable(tablePatient);
        recordDetails.DefaultView.Sort = HiddenFieldExpression.Value + " " + HiddenFieldSortOrder.Value;
        if (recordDetails.Rows.Count > 0)
        {
            GridViewPatientList.DataSource = recordDetails.DefaultView;
            GridViewPatientList.DataBind();
            LabelNoRecords.Visible = false;
        }
        else
        {
            LabelNoRecords.Visible = true;
            LabelNoRecords.Text = "Patient records not found";
        }
    }

    /// <summary>
    /// Check Patients Records File is present on Data folder  
    /// </summary>
    /// <param name="FolderName">Record Type Folder</param>
    /// <param name="PersonId">Patient Id</param>    
    /// <returns>File is present or Not as Boolean</returns>
    public string CheckFile(String FolderName, String PersonId)
    {
        bool fileflag = false;
        DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("Data/" + Session["PracticeFolderName"].ToString() + "/" + FolderName));
        FileInfo[] fileinfo = dirInfo.GetFiles("*.xml");
        if (fileinfo.Length > 0)
        {
            foreach (FileInfo finfo in fileinfo)
            {
                if (finfo.Name.Contains("-" + PersonId + "-"))
                {
                    fileflag = true;
                }
                if (finfo.Name.Contains("Medication") && finfo.Name.Contains("-" + PersonId + "-"))
                {
                    XmlDocument xmldoc = new XmlDocument();
                    xmldoc.Load(finfo.FullName);
                    if (!string.IsNullOrEmpty(xmldoc.SelectSingleNode("Medications").InnerXml))
                    {
                        fileflag = true;
                    }
                    else
                    {
                        fileflag = false;
                    }
                }
            }
        }
        //return fileflag;
        if (fileflag)
        {
            return "Y";
        }
        else
        {
            return "N";
        }

    }
    protected void GridViewPatientList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (DataBinder.Eval(e.Row.DataItem, "PatientName").ToString().Length > 35)
            {
                ((HyperLink)e.Row.Cells[0].FindControl("HyperLinkName")).Text = DataBinder.Eval(e.Row.DataItem, "PatientName").ToString().Substring(0, 33) + "...";
                ((HyperLink)e.Row.Cells[0].FindControl("HyperLinkName")).ToolTip = DataBinder.Eval(e.Row.DataItem, "PatientName").ToString();
            }
        }
    }
}
